#!/bin/sh

# Copyright (c) 2006-2007 XenSource, Inc.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# Very simple Debian install/powerstate script

# Allow the path to the 'xe' binary to be overridden by the XE environment variable
if [ -z "${XE}" ]; then
  XE=xe
fi

if [ ! -e "${HOME}/.xe" ]; then
  read -p "Server name: " SERVER
  read -p "Username: " USERNAME
  read -p "Password: " PASSWORD
  XE="${XE} -s ${SERVER} -u ${USERNAME} -pw ${PASSWORD}"
fi

# Source the inventory file, which tells us amongst other thing the name of
# the management interface
if [ -e @INVENTORY@ ]; then
  . @INVENTORY@
fi
if [ -z "${MANAGEMENT_INTERFACE}" ]; then
  echo No MANAGEMENT_INTERFACE environment varible set: assuming xenbr0
  MANAGEMENT_INTERFACE=xenbr0
fi

# Clone the pre-existing Debian Etch guest template. This template provision a 
# 4GiB root disk, and a 512MiB swap disk on first boot. 
echo "Installing the VM. This operation takes a few seconds..."
VM=`${XE} vm-install new-name-label=debian-etch template="Debian Etch 4.0"`
echo "Installed."

# Find the network associated with the management interface. We'll assume that
# this is the network on which we want a network interface.
NETWORK=`${XE} network-list bridge=${MANAGEMENT_INTERFACE} --minimal`

# Add a VIF linking the VM to the network
VIF=`${XE} vif-create vm-uuid=${VM} network-uuid=${NETWORK} device=0`

# Cause it not to ask for a root password
${XE} vm-param-set uuid=${VM} PV-args="noninteractive"

# Now lets start the VM
echo "Starting VM."
${XE} vm-start uuid=${VM}

# We'll now poll for the network to appear

echo "Waiting for the IP address to appear. This can take a minute or so."
RC=1
while [ ${RC} -ne 0 ]
do
	sleep 5
	IP=`${XE} vm-param-get uuid=${VM} param-name=networks param-key="0/ip"`
	RC=$?
done

# VM is up, and has an IP address. Echo out some useful bits and pieces
echo "Debian Etch VM installed. Uuid=${VM}."
echo "IP address=${IP}."




